package com.chenju.invokechainservice.adapter;

import com.chenju.invokechainservice.common.enums.EasyCode;
import org.objectweb.asm.*;

import java.io.IOException;
import java.lang.reflect.Field;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class ConstantVisitor extends ClassVisitor {
    public ConstantVisitor() {
        super(Opcodes.ASM9);
    }

    @Override
    public FieldVisitor visitField(int access, String name, String descriptor, String signature, Object value) {
        System.out.println(String.format("Constant Field %s : %s", name, value));
        return super.visitField(access, name, descriptor, signature, value);
    }

    @Override
    public MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions) {
        if ("<clinit>".equals(name)) {
            return new MethodVisitor(Opcodes.ASM7) {
                @Override
                public void visitFieldInsn(int opcode, String owner, String name, String descriptor) {
                    if (opcode == Opcodes.PUTSTATIC && "URL_SPLIT".equals(name)) {
                        System.out.println("URL_SPLIT 被赋值");
                    }
                }
            };
        }
        return super.visitMethod(access, name, descriptor, signature, exceptions);
    }

    @Override
    public void visitEnd() {
        super.visitEnd();
    }

    public static void main(String[] args) throws IOException, NoSuchFieldException, IllegalAccessException {
//        Path path = Paths.get("D:\\Project\\springboot-easytest\\invokechain-service\\target\\classes\\com\\chenju\\invokechainservice\\common\\enums\\EasyCode.class");
//        byte[] classBytes = Files.readAllBytes(path);
//        ClassReader cr = new ClassReader(classBytes);
//        cr.accept(new ConstantVisitor(), ClassReader.SKIP_DEBUG);

        Path path = Paths.get("D:\\Project\\springboot-easytest\\invokechain-service\\target\\classes\\com\\chenju\\invokechainservice\\common\\enums\\EasyCode.class");
        byte[] classBytes = Files.readAllBytes(path);
        Class<?> clazz = new CustomClassLoader().defineClass(classBytes);
        Field field = clazz.getField("URL_SPLIT");
        String string = field.get(null).toString();
        System.out.println(string);
    }
}

class CustomClassLoader extends ClassLoader {
    public Class<?> defineClass(byte[] data) {
        return defineClass(null, data, 0, data.length);
    }
}